package com.synjones.zeuscloudweb.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.synjones.zeus.model.web.MenuBean;
import com.synjones.zeus.model.web.RoleBean;
import com.synjones.zeuscloudweb.service.RoleService;
import com.synjones.zeuscloudweb.util.ccl.datastructure.impl.BaseDto;
import com.synjones.zeuscloudweb.util.ccl.util.G4Utils;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.synjones.zeus.model.CodeStr.NUM0;

/**
 * 角色管理
 *
 * @author yys
 * Description: 角色管理
 * @date created in 13:55 2018-01-12
 * Modified by:
 */

@Controller
@RequestMapping("/role")
public class RoleController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    @Qualifier("roleServiceImpl")
    private RoleService roleService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 角色页跳转
     *
     * @param
     * @return String
     * throws
     * @author yys
     * Description:  角色页跳转
     * @date 16:53 2018-01-12
     */
    @RequestMapping(value = "/roleListInfo", method = RequestMethod.GET)
    public String roleListInfo() {
        return "role-list";
    }

    /**
     * 角色添加页跳转
     *
     * @param
     * @return String
     * throws
     * @author yys
     * Description:  角色添加页跳转
     * @date 16:54 2018-01-12
     */
    @RequestMapping(value = "/addRoleInfo", method = RequestMethod.GET)
    public String addRoleInfo() {
        return "role-add";
    }

    /**
     * 修改页跳转
     *
     * @param
     * @return throws
     * @author yys
     * Description:  修改页跳转
     * @date 14:02 2018-01-17
     */
    @RequestMapping(value = "/updateRoleInfo", method = RequestMethod.GET)
    public String updateRoleInfo(Model model, @Param("roleId") String roleId) {
        //角色信息
        RoleBean roleBean = roleService.selectRoleByRoleId(roleId);
        model.addAttribute("role", roleBean);
        return "role-update";
    }

    /**
     * 获取菜单树
     *
     * @param
     * @return throws
     * @author yys
     * Description:  获取菜单树
     * @date 10:44 2018-01-15
     */
    @RequestMapping(value = "/selectTreeMenu", method = RequestMethod.POST)
    public void selectTreeMenu(HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto result = roleService.selectTreeMenu();
        List<MenuBean> menuBeanList = (List<MenuBean>) result.get("data");
        for (MenuBean menuBean : menuBeanList) {
            if (menuBean.getpId().equals(NUM0)) {
                menuBean.setOpen(true);
            }
        }
        pw.write(JSONObject.fromObject(result).toString());
        pw.close();
    }

    /**
     * 添加角色以及角色拥有权限
     *
     * @param roleName 角色名
     * @param menuId   权限菜单ID
     * @param remarks  备注
     * @return throws
     * @author yys
     * Description:  添加角色以及角色拥有权限
     * @date 12:03 2018-01-15
     */
    @RequestMapping(value = "/addRoleMenu", method = RequestMethod.POST)
    public void addRoleMenu(@Param("roleName") String roleName, @Param("menuId") String menuId,
                            @Param("remarks") String remarks, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto jsonDao;
        if (G4Utils.isNotEmpty(roleName)) {
            int count = roleService.selectCountRoleByRoleName(roleName);
            if (count > 0) {
                jsonDao = new BaseDto();
                jsonDao.put("success", new Boolean(false));
                jsonDao.put("msg", "已存在此名称角色请重新命名!");
                jsonDao.put("data", null);
            } else {
                jsonDao = roleService.insertRoleMenu(roleName, menuId, remarks);
            }
        } else {
            jsonDao = new BaseDto();
            jsonDao.put("success", new Boolean(false));
            jsonDao.put("msg", "请求参数出错!");
            jsonDao.put("data", null);
        }
        pw.write(JSONObject.fromObject(jsonDao).toString());
        pw.close();
    }

    /**
     * 修改状态
     *
     * @param response
     * @param roleBean
     * @throws IOException
     */
    @RequestMapping(value = "/updateAvailable", method = RequestMethod.POST)
    public void updateAvailable(HttpServletResponse response, RoleBean roleBean) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto jsonDto = new BaseDto();
        try {
            int upRet = roleService.updateRoleAvailable(roleBean);
            logger.debug("ID为" + roleBean.getRoleId() + "修改AVAILABLE=" + roleBean.getAvailable());
            if (upRet > 0) {
                jsonDto.put("userId", roleBean.getRoleId());
                jsonDto.put("success", new Boolean(true));
                jsonDto.put("msg", "操作成功!");
            } else {
                jsonDto.put("userId", roleBean.getRoleId());
                jsonDto.put("success", new Boolean(false));
                jsonDto.put("msg", "操作失败!");
            }
            pw.write(JSONObject.fromObject(jsonDto).toString());
        } catch (Exception e) {
            jsonDto.put("userId", roleBean.getRoleId());
            jsonDto.put("success", new Boolean(false));
            jsonDto.put("msg", "操作失败请联系管理员!");
            pw.write(JSONObject.fromObject(jsonDto).toString());
        } finally {
            pw.close();
        }
    }

    /**
     * 分页获取角色列表
     *
     * @param
     * @return throws
     * @author yys
     * Description:  分页获取角色列表
     * @date 10:10 2018-01-16
     */
    @RequestMapping(value = "/selectRoleByPage", method = RequestMethod.POST)
    public void selectRoleByPage(HttpServletRequest request, HttpServletResponse response, RoleBean roleBean) throws IOException {
        PrintWriter pw = response.getWriter();
        //直接返回前台
        String draw = request.getParameter("draw");
        //数据起始位置
        String startIndex = request.getParameter("startIndex");
        //每页显示的条数
        String pageSize = request.getParameter("pageSize");
        //获取排序字段
        String orderColumn = request.getParameter("orderColumn");
        //角色名
        String roleName = request.getParameter("roleName");
        if (orderColumn == null) {
            orderColumn = "ROLEID";
        }
        //获取排序方式
        String orderDir = request.getParameter("orderDir");
        if (orderDir == null) {
            orderDir = "ASC";
        }
        if (G4Utils.isNotEmpty(roleName)) {
            roleBean.setRoleName(roleName);
        }
        //分页处理，显示第一页的10条数据
        Page<RoleBean> page = PageHelper.offsetPage((Integer.parseInt(startIndex)), (Integer.parseInt(pageSize)));
        roleService.selectRoleByPage(orderColumn, orderDir, roleBean);
        PageInfo<RoleBean> pageInfo = new PageInfo<>(page);
        Map<Object, Object> info = new HashMap<>();
        info.put("pageData", pageInfo.getList());
        info.put("total", pageInfo.getTotal());
        info.put("draw", draw);
        pw.write(JSONObject.fromObject(info).toString());
        pw.close();
    }
    /**
     * 批量删除角色信息
     *
     * @param roleId 角色ID集合
     * @return throws
     * @author yys
     * Description:  批量删除角色信息
     * @date 14:21 2018-01-16
     */
    @RequestMapping(value = "/deleteRoleByRoleId", method = RequestMethod.POST)
    public void deleteRoleByRoleId(@Param("roleId") String roleId, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto jsonDao;
        if (G4Utils.isNotEmpty(roleId)) {
            jsonDao = roleService.deleteRoleByRoleId(roleId);
        } else {
            jsonDao = new BaseDto();
            jsonDao.put("success", new Boolean(false));
            jsonDao.put("msg", "请求参数出错! 请重新选择");
            jsonDao.put("data", null);
        }
        pw.write(JSONObject.fromObject(jsonDao).toString());
        pw.close();
    }

    /**
     * 获取此角色以拥有的菜单 并以zTree所需数据格式返回
     *
     * @param
     * @return throws
     * @author yys
     * description
     * @date 11:56 2018-01-17
     */
    @RequestMapping(value = "/selectTreeMenuForUpdate", method = RequestMethod.POST)
    public void selectTreeMenuForUpdate(@Param("roleId") String roleId, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        //根据角色Id查询角色菜单关联表 此角色以拥有的菜单集合
        BaseDto result = roleService.selectTreeMenuForUpdate(roleId);
        pw.write(JSONObject.fromObject(result).toString());
        pw.close();
    }


    @RequestMapping(value = "/updateRoleMenu", method = RequestMethod.POST)
    public void updateRoleMenu(RoleBean roleBean, @Param("menuId") String menuId,
                               HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        BaseDto jsonDao;
        if (G4Utils.isNotEmpty(roleBean)) {
            jsonDao = roleService.updateRoleAndRoleMenu(roleBean, menuId);
        } else {
            jsonDao = new BaseDto();
            jsonDao.put("success", new Boolean(false));
            jsonDao.put("msg", "请求参数出错!");
            jsonDao.put("data", null);
        }
        pw.write(JSONObject.fromObject(jsonDao).toString());
        pw.close();
    }
}
